package com.auto.learning.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler.Callback;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebSettings.TextSize;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.auto.learning.R;
import com.auto.learning.activity.BaseWebViewClient.OnCustomerUrlLoadingListener;
import com.auto.learning.bean.Banner_H5;
import com.auto.learning.event.listener.DialogListener;
import com.auto.learning.net.HttpCommonInfo;
import com.auto.learning.net.HttpRequestHelper;
import com.auto.learning.sharesdk.tools.ShareOpUtils;
import com.auto.learning.tools.CookiesUtil;
import com.auto.learning.tools.FileUtil;
import com.auto.learning.tools.IAlertDialogListener;
import com.auto.learning.tools.ImageUtil;
import com.auto.learning.tools.TemporaryVariable;
import com.auto.learning.view.CommonAlertDialog;
import com.auto.learning.view.ShareView;
import com.auto.learning.view.SharedPreferencesUtils;

public class WebActivity extends BaseWebViewActivity implements Callback{
	private final String TAG = WebActivity.class.getSimpleName();
	String baseUrl;
	String dojs;
	String param;
	// ImageView imgBar;
	private boolean isLoadSkin = false;
	Context mContext;
	TextView textView1;// 标题
	WebView webView;
	// ImageView setting_back;// 返回按钮
	LinearLayout login_btn_back;// 返回按钮
	RelativeLayout activity_base_title;// 标题
	String title;
	boolean fromSD;// 优先级属性从sd卡读取
	RelativeLayout weblayout_NaviBar, webviewlayout;// 导航和浏览器布局
	boolean isSkip;
	int rotation;
	int returnView;// 1直接关闭页面
	BaseWebViewClient baseWebViewClient;
	String loginCallback;// 登录返回调用方法
	HashMap<String, String> caches;// 浏览器页面临时缓存,关闭时要清空
	ValueCallback<Uri> mUploadMessage;
	public static final int FILECHOOSER_RESULTCODE = 1;
	private static final int REQ_CAMERA = FILECHOOSER_RESULTCODE + 1;
	private static final int REQ_CHOOSE = REQ_CAMERA + 1;
	private static final int REQ_PAY = 8888;// 支付财付通
	private static final int REQ_PAY_RESULT = 8889;// 支付财付通
	private String PayCallBack;// 财富通支付回调方法
	public String CommonCallBack;// 通用回调。用完清空
	ImageView tips_homeView;// 提示层
	private LinearLayout activity_base_more;
	boolean showtitle;
	boolean unneedwebcache;// 1 切换成WebSettings.LOAD_NO_CACHE
	int mm;
	TextView tv_datetime;
	public PopupWindow pop;
	boolean isClose;
	Banner_H5 banner_H5;

	// boolean backtoHome;// 返回到home
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setConfigCallback((WindowManager) getApplicationContext()
		// .getSystemService(Context.WINDOW_SERVICE));
		caches = new HashMap<String, String>();
		TemporaryVariable.activities.push(this);
	}
	
	@Override
	public void init() {
		Intent intent = getIntent();
		// backtoHome = intent.getBooleanExtra("backtoHome", false);
		baseUrl = intent.getStringExtra("url");// 只要目录跟文件名就可以了
		fromSD = intent.getBooleanExtra("fromSD", false);
		isSkip = intent.getBooleanExtra("isSkip", false);
		rotation = intent.getIntExtra("rotation", 0);
		returnView = intent.getIntExtra("returnView", 0);
		showtitle = intent.getBooleanExtra("showtitle", false);
		unneedwebcache = intent.getBooleanExtra("unneedwebcache", false);
		isClose=intent.getBooleanExtra("isClose", false);
		
		banner_H5 = (Banner_H5) intent.getSerializableExtra("h5_model");
		
		
		if (baseUrl != null && !baseUrl.contains("http")) {
			if (fromSD) {
				baseUrl =  "file:///" + baseUrl;
			} else {
				baseUrl = "file:///android_asset/" + baseUrl;
			}
		}
		if (rotation == 1) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// 强制横屏,默认竖屏
		} else if (rotation == 2) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);// 自动切换
		}

		dojs = intent.getStringExtra("dojs");
		param = intent.getStringExtra("param");
		title = intent.getStringExtra("title");
		mContext = this;
		setContentView(R.layout.activity_web);
		weblayout_NaviBar = (RelativeLayout) findViewById(R.id.weblayout_NaviBar);
		activity_base_title = (RelativeLayout) findViewById(R.id.activity_base_title);
		webviewlayout = (RelativeLayout) findViewById(R.id.webviewlayout);
		activity_base_more = (LinearLayout) findViewById(R.id.activity_base_more);
		if (showtitle) {
			activity_base_title.setVisibility(View.VISIBLE);
			textView1 = (TextView) findViewById(R.id.activity_base_titlename);
			if (!TextUtils.isEmpty(title)) {
				textView1.setText(title);
			}
		}
		// imgBar = (ImageView) findViewById(R.id.img_bar);

		login_btn_back = (LinearLayout) findViewById(R.id.activity_base_back);
		login_btn_back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		activity_base_more.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (banner_H5 != null) {
					String content = banner_H5.getShareSmallTitle();
					String title = banner_H5.getShareTitle();
					String url = banner_H5.getShareUrl().replace("{userId}", String.valueOf(SharedPreferencesUtils.getParam(WebActivity.this, HttpRequestHelper.USERID, 0)));
					new ShareView(WebActivity.this, WebActivity.this).setTitle(title).setUrl(url).setImageUrl(banner_H5.getShareImg()).setId(banner_H5.getId()+"").setContent(content).setType(6).show(findViewById(R.id.main_view));
				}
			}
		});
		
		if (banner_H5 != null) {
			if (banner_H5.getIsShare() == 2) {
				activity_base_more.setVisibility(View.VISIBLE);
			}else {
				activity_base_more.setVisibility(View.GONE);
			}
		}else {
			activity_base_more.setVisibility(View.GONE);
		}

		webView = null;
		webView = (WebView) findViewById(R.id.mainwebview);
		// webView.setVerticalScrollBarEnabled(false);
		// webView.setHorizontalScrollBarEnabled(false);
		// RelativeLayout.LayoutParams lParams = new
		// RelativeLayout.LayoutParams(
		// -1, -1);
		// webviewlayout.addView(webView, lParams);

		// 换肤
		// ThemeInfoManger them = ThemeInfoManger.getInstance(WebActivity.this);
		// if (!"normal".equals(them.getFileName())) {
		// titleBg.setBackgroundDrawable(them.getDrawable("bg_title"));
		// imgBar.setBackgroundDrawable(them.getDrawable("img_bar"));
		// webView.setBackgroundColor(them.getColor("bg_color"));
		// isLoadSkin = true;
		// }

		webView.clearCache(true);
		webView.clearHistory();
		webView.requestFocus();
		/*CTSCmd cmd = new CTSCmd(webView);
		cmd.addobj("com.isoftstone.webviewcomponent.webapp.ui.CTSTransfer",
				"Transfer");

		cmd.addobj("com.isoftstone.webviewcomponent.webapp.ui.CTSTool", "Tools");
		cmd.addobj("com.isoftstone.webviewcomponent.webapp.ui.Network",
				"Network");
		cmd.addobj("com.isoftstone.webviewcomponent.webapp.ui.WebCache",
				"NHWebCache");
		cmd.addobj("com.isoftstone.webviewcomponent.webapp.ui.DataBaseObj",
				"Database");
		cmd.addobj("com.isoftstone.webviewcomponent.webapp.ui.CTSBaiduStatistics", "BaiduStatistical");

		webView.addJavascriptInterface(cmd, "ctsCmd");*/
		baseWebViewClient = new BaseWebViewClient() {
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				if (webView != null) {
					if (!webView.getSettings().getLoadsImagesAutomatically()) {
						webView.getSettings().setLoadsImagesAutomatically(true);
					}
				}
				if (dojs != null) {
					if (param == null) {
						loadJS(dojs, "");
					} else {
						loadJS(dojs, param);
					}
				}
			}

			// 一个work around方法：解决Android 3.0~4.0下WebView 对锚点链接不支持的bug
			// http://blog.csdn.net/rongwenbin/article/details/39637675
			@Override
			public void onReceivedError(WebView view, int errorCode,

			String description, String failingUrl) {

				if (failingUrl.contains("#")) {
					String[] temp;
					temp = failingUrl.split("#");
					view.loadUrl(temp[0]); // load page without internal
					try {

						Thread.sleep(400);

					} catch (InterruptedException e) {

						e.printStackTrace();

					}
					view.goBack();
					view.goBack();

				}

			}

			@Override
			public void receivedSslError(WebView view, SslErrorHandler handler,
					SslError error) {
				// TODO Auto-generated method stub

			}

			@Override
			public void receivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				// TODO Auto-generated method stub

			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				// LogUtil.d("ddddd","webview load:",url);

				try {
					url = java.net.URLDecoder.decode(url, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (url.toLowerCase().indexOf("requestnative:{\"sueccess\"") > -1) {
					// 财付通付款
					int startPos = url.indexOf("{\"sueccess\"");
					String strJson = url.substring(startPos);
					JSONObject jsonObject = null;
					try {
						jsonObject = new JSONObject(strJson);
						Intent data = new Intent();
						data.putExtra("data", jsonObject.toString());
						data.putExtra("js", PayCallBack);
						setResult(REQ_PAY_RESULT, data);
						finish();
					} catch (JSONException e) {
						e.printStackTrace();
					}
					return true;
				}
				if (url.indexOf("returnhome:") > -1) {
					setResult(88);
					finish();

					return true;
				} else if (url.indexOf("returnlogin:") > -1) {
					Log.d(TAG, "send no authentication broadcast");
					return true;
				}
				return super.shouldOverrideUrlLoading(view, url);
			}
		};

		baseWebViewClient.addOnCustomerUrlLoadingListener(mCustomerUrlLoadingListener);

		initWebView(webView, baseWebViewClient, baseWebChromeClient);
		if (unneedwebcache) {
			webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		}

		String textsizes = null;
		int textsize;
		if (textsizes != null && !textsizes.equals("")) {
			textsize = Integer.valueOf(textsizes);
		} else
			textsize = 1;
		updateFontzise(textsize);
		tips_homeView = (ImageView) findViewById(R.id.tips_homeView);
		// if (Build.VERSION.SDK_INT >= 19) {
		// webView.getSettings().setLoadsImagesAutomatically(true);
		// } else {
		// webView.getSettings().setLoadsImagesAutomatically(false);
		// }
		// RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
		// -1, -2);
		// weblayout_NaviBar.addView(getHomeTool(),lp);

	}


	public void showTips_View(String imagepath) {
		try {
			// showTipsview(null);
			Drawable drawable = ImageUtil.getDrawble(imagepath);
			if (drawable != null) {
				tips_homeView.setImageDrawable(drawable);
				tips_homeView.setVisibility(View.VISIBLE);
				tips_homeView.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						tips_homeView.setVisibility(View.GONE);
					}
				});
			} else {
				
			}
		} catch (OutOfMemoryError e) {
			System.gc();
			System.runFinalization();
			showTips_View(imagepath);
		}
	}

	@Override
	public void load() {
		// TODO Auto-generated method stub
		// baseUrl = "file:///android_asset/lottery/index.html?json=";

		// CookieSyncManager cookieSyncManager =
		// CookieSyncManager.createInstance(BaseWebViewActivity.this);

		// CookieManager cookieManager = CookieManager.getInstance();
		// String domainName="gbssdev.infinitus.com.cn";
		//
		//
		// String cookieString=cookieManager.getCookie(domainName);
		//
		// LogUtil.d("HttpCookies", "WebKit Cookies market:"+cookieString);

		CookiesUtil.setWebViewCookies(this);
		loadWebViewData(baseUrl);
	}


	private OnCustomerUrlLoadingListener mCustomerUrlLoadingListener = new OnCustomerUrlLoadingListener() {

		@Override
		public void onCustomerUrlLoading(WebView view, String url) {
			// TODO Auto-generated method stub
			// Intent intent = new Intent();
			// intent.setClass(getApplicationContext(), MarketActivity.class);
			// startActivity(intent);
			// overridePendingTransition(R.anim.anim_enter, R.anim.anim_exit);
			// finish();
		}
	};

	public void onDestroy() {
		TemporaryVariable.activities.removeElement(this);
		try {
			caches.clear();
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
		overridePendingTransition(R.anim.anim_enter, R.anim.anim_exit);
	};

	/**
	 * 按钮监听器
	 */
	private IAlertDialogListener exitListener = new IAlertDialogListener() {

		@Override
		public void okButtonClick(Dialog dialog) {
			// TODO Auto-generated method stub
			dialog.cancel();
		}

		@Override
		public void cancelButtonClick(Dialog dialog) {
			// TODO Auto-generated method stub
			dialog.cancel();
		}
	};
	BaseWebChromeClient baseWebChromeClient = new BaseWebChromeClient(this) {
		@Override
		public boolean onJsAlert(WebView view, String url, final String message, final JsResult result) {
			try {
				CommonAlertDialog alertDialog = new CommonAlertDialog(mContext);
				alertDialog.setTextMessage(message);
				alertDialog.setShowTitle(true);
				String[] a = { getResources().getString(R.string.ok)};
				alertDialog.setBtns(new DialogListener() {
					
					@Override
					public void otherButtonClick(Dialog dialog) {
						
					}
					
					@Override
					public void okButtonClick(Dialog dialog) {
						result.confirm();
						dialog.cancel();
					}
					
					@Override
					public void cancelButtonClick(Dialog dialog) {
						result.cancel();
						dialog.cancel();
					}
				}, a);
				alertDialog.show();
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
			return true;
		}

		@Override
		public void onConsoleMessage(final String message,
				final int lineNumber, final String sourceID) {
			String fileError = "Not allowed to load local resource: ";
			try {

				// CommonDialog exitReminder = new CommonDialog(mContext,
				// R.style.dialog, exitListener);
				String msg = message + "<br>Line: " + lineNumber + "<br>URL: "
						+ sourceID;

				printlnFile(msg);
				/**
				 * 浏览器捕捉到/login时，强制提醒重新登录 修改人：黄志强 2014-8-22 10:21
				 */
				if (msg.contains("/login")) {
					setResult(899);
					finish();

				}
				// super.onConsoleMessage(message, lineNumber, sourceID);
				// exitReminder.setAlertMsg(msg);
				// exitReminder.setCancelable(true);
				// exitReminder.setCanceledOnTouchOutside(false);
				// exitReminder.setAlertBtnCount(false);
				// exitReminder.setSingleBtnText(mContext
				// .getString(R.string.dialog_ok));
				// exitReminder.show();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	
	private void printlnFile(String msg) throws IOException {
		//保存JS错误
		File f = new File(FileUtil.getFileCachePath() + "/logs/JSerror",
				getTime().replaceAll(":", "_") + ".txt");
		if (!f.getParentFile().exists()) {
			f.getParentFile().mkdirs();
		}
		f.createNewFile();
		PrintWriter p = new PrintWriter(new OutputStreamWriter(
				new FileOutputStream(f), "gbk"));
		p.println(msg);
		p.flush();
		p.close();
	}


	public static String getTime() {
		Calendar cal = Calendar.getInstance();
		String ty = String.valueOf(cal.get(Calendar.YEAR));
		String tm = String.valueOf(cal.get(Calendar.MONTH) + 1);
		String td = String.valueOf(cal.get(Calendar.DATE));
		String th = String.valueOf(cal.get(Calendar.HOUR_OF_DAY));
		String tmin = String.valueOf(cal.get(Calendar.MINUTE));
		String ts = String.valueOf(cal.get(Calendar.SECOND));
		if (tm.length() < 2)
			tm = "0" + tm;
		if (td.length() < 2)
			td = "0" + td;
		if (th.length() < 2)
			th = "0" + th;
		if (tmin.length() < 2)
			tmin = "0" + tmin;
		if (ts.length() < 2)
			ts = "0" + ts;
		String time = ty + "-" + tm + "-" + td + " " + th + ":" + tmin + ":"
				+ ts;
		return time;
	}

	public void setTitle(String text) {
		if (textView1 != null) {
			textView1.setText(text + "");
		}

	}

	String backaction;

	/**
	 * 设置返回键动作,修改人：黄志强，时间 2014-8-18 14:00
	 * 
	 * @action 为null或空时 正常返回，其他情况调用js功能。
	 */
	public void setOnback(String action) {
		backaction = action;
	}

	private static final String SCAN = "scan";
	private static final String ENCODE = "encode";
	private static final String CANCELLED = "cancelled";
	private static final String FORMAT = "format";
	private static final String TEXT = "text";
	private static final String DATA = "data";
	private static final String TYPE = "type";

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
	}

	/**
	 * 调用js方法
	 * @param js
	 * @param param
	 */
	public void loadJS(String js, String param) {
		Log.d("xxD", "javascript:" + js + "(" + param + ")");
		webView.loadUrl("javascript:" + js + "(" + param + ")");
	}
	

	@Override
	public void onBackPressed() {
		if (returnView == 1) {
			finish();
			return;
		}
		if (backaction != null && !backaction.equals("")) {
			loadJS(backaction, "");
			return;
		}
		if (webView.canGoBack()) {
			webView.goBack();
		} else {
			finish();
		}
		// super.onBackPressed();
	}

	/**
	 * 更新字体大小
	 * 
	 * @param size
	 */
	public void updateFontzise(int size) {
		TextSize data = WebSettings.TextSize.NORMAL;
		switch (size) {
		case 0:
			data = WebSettings.TextSize.SMALLER;
			break;
		case 1:
			data = WebSettings.TextSize.NORMAL;
			break;
		case 2:
			data = WebSettings.TextSize.LARGER;
			break;
		case 3:
			data = WebSettings.TextSize.LARGEST;
			break;
		}
		webView.getSettings().setTextSize(data);
	}

	// @Override
	// public boolean onCreateOptionsMenu(Menu menu) {
	// menu.add(0, 0, 0, "显示log");
	// return super.onCreateOptionsMenu(menu);
	// }


	public void setConfigCallback(WindowManager windowManager) {
		try {
			Field field = WebView.class.getDeclaredField("mWebViewCore");
			field = field.getType().getDeclaredField("mBrowserFrame");
			field = field.getType().getDeclaredField("sConfigCallback");
			field.setAccessible(true);
			Object configCallback = field.get(null);

			if (null == configCallback) {
				return;
			}

			field = field.getType().getDeclaredField("mWindowManager");
			field.setAccessible(true);
			field.set(configCallback, windowManager);
		} catch (Exception e) {
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

		if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
			// WebContent.lineChartView.Init("");
		} else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
			// WebContent.lineChartView.Init("");
		}
	}

	/***
	 * -------------------------------------图片选择-------------------------------
	 */

	/**
	 * 检查SD卡是否存在
	 * 
	 * @return
	 */
	public final boolean checkSDcard() {
		boolean flag = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
		if (!flag) {
			Toast.makeText(this, "请插入手机存储卡再使用本功能", Toast.LENGTH_SHORT).show();
		}
		return flag;
	}

	String compressPath = "";

	protected final void selectImage() {
		if (!checkSDcard())
			return;
		String[] selectPicTypeStr = { "拍照", "相册" };
		new AlertDialog.Builder(this).setItems(selectPicTypeStr,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						// 相机拍摄
						case 0:
							openCarcme();
							break;
						// 手机相册
						case 1:
							// chosePic2();
							chosePic();
							break;
						default:
							break;
						}
						compressPath = Environment
								.getExternalStorageDirectory().getPath()
								+ "/fuiou_wmp/temp";
						new File(compressPath).mkdirs();
						compressPath = compressPath + File.separator
								+ "compress.jpg";
					}
				}).show();
	}

	public String imagePaths;
	Uri cameraUri;

	/**
	 * 打开照相机
	 */
	public void openCarcme() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		imagePaths = Environment.getExternalStorageDirectory().getPath() + "/fuiou_wmp/temp/" + (System.currentTimeMillis() + ".jpg");
		// 必须确保文件夹路径存在，否则拍照后无法完成回调
		File vFile = new File(imagePaths);
		if (!vFile.exists()) {
			File vDirPath = vFile.getParentFile();
			vDirPath.mkdirs();
		} else {
			if (vFile.exists()) {
				vFile.delete();
			}
		}
		cameraUri = Uri.fromFile(vFile);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
		startActivityForResult(intent, REQ_CAMERA);
	}

	/**
	 * 拍照结束后
	 */
	private void afterOpenCamera() {/*
		File f = new File(imagePaths);
		addImageGallery(f);
		File newFile = PicFileUtils.compressFile(f.getPath(), compressPath);
	*/}

	/** 解决拍照后在相册中找不到的问题 */
	private void addImageGallery(File file) {
		ContentValues values = new ContentValues();
		values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
		values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
		getContentResolver().insert(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
	}

	/**
	 * 本地相册选择图片
	 */
	private void chosePic() {/*
		PicFileUtils.delFile(compressPath);
		Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); // "android.intent.action.GET_CONTENT"
		String IMAGE_UNSPECIFIED = "image/*";
		innerIntent.setType(IMAGE_UNSPECIFIED); // 查看类型
		Intent wrapperIntent = Intent.createChooser(innerIntent, null);
		startActivityForResult(wrapperIntent, REQ_CHOOSE);
	*/}


	/**
	 * 选择照片后结束
	 * 
	 * @param data
	 */
	private Uri afterChosePic(Intent data) {
		/*
		// 获取图片的路径：
		String[] proj = { MediaStore.Images.Media.DATA };
		// 好像是android多媒体数据库的封装接口，具体的看Android文档
		Cursor cursor = managedQuery(data.getData(), proj, null, null, null);
		if (cursor == null) {
			Toast.makeText(this, "上传的图片仅支持png或jpg格式", Toast.LENGTH_SHORT)
					.show();
			return null;
		}
		// 按我个人理解 这个是获得用户选择的图片的索引值
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		// 将光标移至开头 ，这个很重要，不小心很容易引起越界
		cursor.moveToFirst();
		// 最后根据索引值获取图片路径
		String path = cursor.getString(column_index);
		if (path != null
				&& (path.endsWith(".png") || path.endsWith(".PNG")
						|| path.endsWith(".jpg") || path.endsWith(".JPG"))) {
			File newFile = PicFileUtils.compressFile(path, compressPath);
			return Uri.fromFile(newFile);
		} else {
			Toast.makeText(this, "上传的图片仅支持png或jpg格式", Toast.LENGTH_SHORT)
					.show();
		}*/
		return null;
	}

	private String getContactPhone(Cursor cursor) {
		int phoneColumn = cursor
				.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
		int phoneNum = cursor.getInt(phoneColumn);
		String result = "";
		if (phoneNum > 0) {
			// 获得联系人的ID号
			int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
			String contactId = cursor.getString(idColumn);
			// 获得联系人电话的cursor
			Cursor phone = application.getContentResolver().query(
					ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
					null,
					ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "="
							+ contactId, null, null);
			if (phone.moveToFirst()) {
				for (; !phone.isAfterLast(); phone.moveToNext()) {
					int index = phone
							.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
					int typeindex = phone
							.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
					int phone_type = phone.getInt(typeindex);
					String phoneNumber = phone.getString(index);
					result = phoneNumber;
					// switch (phone_type) {//电话类型
					// case 2:
					// result = phoneNumber;
					// break;
					//
					// default:
					// break;
					// }
				}
				if (!phone.isClosed()) {
					phone.close();
				}
			}
		}
		return result;
	}

	@Override
	public boolean handleMessage(Message msg) {
		ShareOpUtils.handleShareCallBack(this, msg);
		return false;
	}

}
